const { app, BrowserWindow, nativeImage, ipcMain, Tray, Menu } = require('electron/main')
const path = require('node:path')
const { shell } = require('electron');

const companyService = require('../node/service/companyService')
const projectService = require('../node/service/projectService')
const itemService = require('../node/service/itemService')
const userService = require('../node/service/userService')
const bookmarkService = require('../node/service/bookmarkService')
const dbService = require('../node/service/dbService')

const { coreConfig, initSql } = require('../node/db/db')
initSql()

var win;

const menuTemplate = [
    {
        label: '文件',
        submenu: [
            { label: '新建', accelerator: 'CmdOrCtrl+N', click: () => { console.log('新建文件'); } },
            { label: '打开', accelerator: 'CmdOrCtrl+O', click: () => { console.log('打开文件'); } },
            { type: 'separator' }, // 分隔线
            { label: '退出', accelerator: 'CmdOrCtrl+Q', role: 'quit' }
        ]
    },
    {
        label: '编辑',
        submenu: [
            { label: '撤销', accelerator: 'CmdOrCtrl+Z', role: 'undo' },
            { label: '重做', accelerator: 'Shift+CmdOrCtrl+Z', role: 'redo' },
            { type: 'separator' },
            { label: '剪切', accelerator: 'CmdOrCtrl+X', role: 'cut' },
            { label: '复制', accelerator: 'CmdOrCtrl+C', role: 'copy' },
            { label: '粘贴', accelerator: 'CmdOrCtrl+V', role: 'paste' },
        ]
    },
    {
        label: '帮助',
        role: 'help',
        submenu: [
            { label: '关于', click: () => { win.webContents.send('update-route', 'about') } }
        ]
    }
]

const createWindow = () => {
    win = new BrowserWindow({
        title: coreConfig.appName,
        autoHideMenuBar: true,
        width: 1000,
        height: 800,
        icon: path.join(__dirname, '../config/icons/32x32.png'),
        webPreferences: {
            preload: path.join(__dirname, 'preload.js')
        }
    })
    win.setBackgroundColor('#eee')
    
    win.loadFile(path.join(__dirname, '../core/index.html'))

    ipcMain.handle('company:add', (event, company) => companyService.add(company))
    ipcMain.handle('company:delete', (event, companyId) => companyService.delete(companyId))
    ipcMain.handle('company:update', (event, company) => companyService.update(company))
    ipcMain.handle('company:get', (event, companyId) => companyService.get(companyId))
    ipcMain.handle('company:getAll', (event) => companyService.getAll())

    ipcMain.handle('project:add', (event, entity) => projectService.add(entity))
    ipcMain.handle('project:delete', (event, entityId) => projectService.delete(entityId))
    ipcMain.handle('project:update', (event, entity) => projectService.update(entity))
    ipcMain.handle('project:get', (event, entityId) => projectService.get(entityId))
    ipcMain.handle('project:getAll', (event) => projectService.getAll())

    ipcMain.handle('item:add', (event, entity) => itemService.add(entity))
    ipcMain.handle('item:delete', (event, entityId) => itemService.delete(entityId))
    ipcMain.handle('item:update', (event, entity) => itemService.update(entity))
    ipcMain.handle('item:get', (event, entityId) => itemService.get(entityId))
    ipcMain.handle('item:getAll', (event) => itemService.getAll())

    ipcMain.handle('bookmark:add', (event, entity) => bookmarkService.add(entity))
    ipcMain.handle('bookmark:delete', (event, entityId) => bookmarkService.delete(entityId))
    ipcMain.handle('bookmark:update', (event, entity) => bookmarkService.update(entity))
    ipcMain.handle('bookmark:get', (event, entityId) => bookmarkService.get(entityId))
    ipcMain.handle('bookmark:getAll', (event) => bookmarkService.getAll())

    ipcMain.handle('user:get', (event) => userService.get())
    ipcMain.handle('user:update', (event, entity) => userService.update(entity))

    ipcMain.handle('db:save', (event) => dbService.saveDB())
    ipcMain.handle('config:get', (event) => {
        return coreConfig
    })
    ipcMain.handle('common:openLink', (event, link) => {
        shell.openExternal(link);
    })

    win.on("close", (e) => {  
        e.preventDefault();
        win.hide()
    })

    // const mainMenu = Menu.buildFromTemplate(menuTemplate);
    // Menu.setApplicationMenu(mainMenu);

    // const child = new BrowserWindow({ parent: win })
    // child.show()

    // const child = new BrowserWindow({ parent: win, modal: true, show: false })
    // child.loadFile('./index.html')
    // child.once('ready-to-show', () => {
    //     child.show()
    // })

    // win.once('ready-to-show', () => {
    //     win.show()
    // })
}

app.whenReady().then(() => {
    const icon = nativeImage.createFromPath(path.join(__dirname, '../config/icons/32x32.png'),)
    tray = new Tray(icon)
    const contextMenu = Menu.buildFromTemplate([
        { label: '显示应用', click: () => { win.show(); } },
        { label: '退出', click: () => { win.destroy(); app.quit(); } }
    ])
    tray.setContextMenu(contextMenu)
    tray.setToolTip(coreConfig.appName)

    createWindow()

    ipcMain.handle('ping', () => 'pong')

    app.on('activate', () => {
        if (BrowserWindow.getAllWindows().length === 0) {
            createWindow()
        }
    })
})

app.on('window-all-closed', (e) => {
    if (process.platform !== 'darwin') {
        app.quit()
    }
})
